<template>
    <div class="container">
        <Breadcrumb :items="['menu.list', 'menu.list.EquipmentManagement']" />
        <a-card class="general-card" title="网点管理">
            <a-row>
                <a-col>
                    <a-form :model="formData" label-align="left" auto-label-width>
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item label="网点名称">
                                    <a-input v-model="formData.name" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="时间">
                                    <a-date-picker :time-picker-props="{ defaultValue: '00:00:00' }"
                                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                        v-model="formData.createdFrom" style="width: 100%;" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="网点位置">
                                    <a-input v-model="formData.location" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="网点类型">
                                    <a-select :style="{ width: '100%' }" v-model="formData.deviceType" placeholder="请选择"
                                        allow-clear>
                                        <a-option :value="2">电吹风 </a-option>
                                        <a-option :value="1">插座</a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <div class="search-btn">
                                    <a-button style="background: #3E3E69;color: #FFFFFF;"
                                        @click="onPageChange(1)">查询</a-button>
                                    <a-button type="primary" @click="openPage('新增')">新增</a-button>
                                    <a-button type="primary" status="success">导出</a-button>
                                    <a-button type="primary" @click="plxz">批量下载</a-button>
                                    <a-button type="primary" @click="yisjd">批量设置运营时间段</a-button>
                                </div>

                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
            </a-row>
        </a-card>

        <div class="container-table">
            <a-card class="general-card">
                <!-- :scroll="{ x: 270 }" -->
                <a-table :virtual-list-props="{ height: 460 }" :loading="loading" :scroll="{
                    x: '120%',
                    y: '100%'
                }" :columns="columns" row-key="id" :row-selection="{
                    type: 'checkbox',
                    showCheckedAll: true,
                    onlyCurrent: false,

                }" v-model:selectedKeys="selectedKeys" :data="tableList" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="pagesizechange">
                    <!-- <template #images="{ record }">
                        <a-image v-if="record.images" width="50" :src="record.images" />
                        <a-image v-else width="50" height="50" src="some-error.png" />
                    </template> -->
                    <template #deviceType="{ record }">
                        {{ record.deviceType == 1 ? '插板' : record.deviceType == 2 ? '吹风机' : '未知' }}
                    </template>
                    <template #status="{ record }">
                        {{ record.status == 'NORMAL' ? '正常' : record.deviceType == 'DAMAGED' ? '维修' : record.deviceType
                            == 'OFFLINE' ? '离线' : '未知' }}
                    </template>
                    <template #qrCodeUrl="{ record }">
                        <a-image v-if="record.qrCodeUrl" width="50" :src="qrCodeUrl(record.qrCodeUrl)" />
                        <a-image v-else width="50" height="50" src="some-error.png" />
                    </template>
                    <template #operations="{ record }">
                        <a-button type="text" size="small" @click="downloadQRCode(record)">
                            下载二维码
                        </a-button>

                        <a-button type="text" size="small" @click="openPage('编辑', record)">
                            编辑
                        </a-button>
                        <a-button type="text" size="small" @click="openPage('查看', record)">
                            查看
                        </a-button>
                        <a-popconfirm content="确认是否删除?" type="warning" @ok="deleteOneOrder(record.id)">
                            <a-button type="text" status="danger" size="small">
                                删除
                            </a-button>
                        </a-popconfirm>
                    </template>
                </a-table>
            </a-card>
        </div>



        <a-modal v-model:visible="isShowEdit">
            <template #title>
                {{ isShowEditNaame }}
            </template>
            <div>
                <a-spin class="w-full" :loading="loadingEdit" tip="创建中...">
                    <a-form ref="formRef" :model="form" layout="vertical">
                        <a-form-item :rules="[{ required: true, message: '网点型号必填' }]" field="deviceType" label="网点型号">
                            <a-select :style="{ width: '100%' }" v-model="form.deviceType" placeholder="请选择">
                                <a-option :value="2">电吹风 </a-option>
                                <a-option :value="1">插座</a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '网点名称必填' }]" field="name" label="网点名称">
                            <a-input v-model="form.name" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '厂商必填' }]" field="manufacturer" label="厂商">
                            <a-input v-model="form.manufacturer" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '通道类型必填' }]" field="channel" label="通道类型">
                            <a-select :style="{ width: '100%' }" v-model="form.channel" placeholder="请选择">
                                <a-option value="LEFT">LEFT</a-option>
                                <a-option value="RIGHT">RIGHT</a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '所属终端必填' }]" field="imei" label="所属终端">
                            <a-select :style="{ width: '100%' }" v-model="form.imei" placeholder="请选择"
                                @dropdown-reach-bottom="handleReachBottom" @search="handleSearch" allow-search>
                                <a-option v-for="(item, index) in imeiList" :key="index" :value="item.imei">{{ item.name
                                    }}</a-option>
                            </a-select>
                        </a-form-item>

                        <a-form-item :rules="[{ required: true, message: '网点位置必填' }]" field="location" label="网点位置">
                            <a-input v-model="form.location" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item v-if="isShowEditNaame == '编辑'"  label="上午时间段">
                            <a-time-picker v-model="form.sw" type="time-range" format="HH:mm" disableConfirm
                                :disabledHours="() => [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]"
                                style="width: 252px;" />
                        </a-form-item>
                        <a-form-item v-if="isShowEditNaame == '编辑'"  label="下午时间段">
                            <a-time-picker v-model="form.xw" type="time-range" format="HH:mm" disableConfirm
                                :disabledHours="() => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"
                                style="width: 252px;" />
                        </a-form-item>
                        <!-- <a-form-item label="图片">
                            <a-upload list-type="picture-card" :limit="1" action="/" :default-file-list="fileList"
                                image-preview :custom-request="customRequest" />
                        </a-form-item>  -->
                    </a-form>
                </a-spin>
            </div>
            <template #footer>
                <a-button @click="isShowEdit = false">取消</a-button>
                <a-button type="primary" @click="handleOk"
                    :disabled="isShowEditNaame == '查看' ? true : false">提交</a-button>
            </template>
        </a-modal>

        <a-modal v-model:visible="visibletimer">
            <template #title>
                运营时间段
            </template>
            <a-form ref="formReftimer" :model="timerList">
                <a-form-item :rules="[{ required: true, message: '时间必填' }]" field="sw" label="上午时间段">
                    <a-time-picker v-model="timerList.sw" type="time-range" format="HH:mm" disableConfirm
                        :disabledHours="() => [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]" style="width: 252px;" />
                </a-form-item>
                <a-form-item :rules="[{ required: true, message: '时间必填' }]" field="xw" label="下午时间段">
                    <a-time-picker v-model="timerList.xw" type="time-range" format="HH:mm" disableConfirm
                        :disabledHours="() => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]" style="width: 252px;" />
                </a-form-item>
            </a-form>
            <template #footer>
                <a-button @click="visibletimer = false">取消</a-button>
                <a-button type="primary" @click="handleOktimer">提交</a-button>
            </template>
        </a-modal>

        <Downloadpic ref="downloadpic" />
    </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue';

import { devicfindAll, devicesadd, wechatfindByDeviceSn, end_backupdate, devicesdelete, repairsupload } from '@/api/hairdryer'
import { recordsfindAll, bulkusetime } from '@/api/hairdryer'
import { baseUrl } from "@/api/interceptor";


import Downloadpic from './downloadpic.vue'

//选择时间
let forTimer = ref({
})
let timerList = ref({})
const yisjd = () => {
    if (selectedKeys.value.length == 0) {
        return Message.warning('请选择网点')
    }

    visibletimer.value = true

    forTimer.value.deviceIds = selectedKeys.value.join()

    console.log(forTimer.value);

}
const visibletimer = ref(false);
let formReftimer = ref()
const handleOktimer = async () => {
    let rs = await formReftimer.value.validate();
    if (rs) return


    forTimer.value.useTime = `${timerList.value.sw[0]}-${timerList.value.sw[1]}|${timerList.value.xw[0]}-${timerList.value.xw[1]}`


    try {
        let res = await bulkusetime(forTimer.value)
        Message.success('新增成功')
        getdevicfindAll() //获取列表
        visibletimer.value = false;

    } catch (error) {
        visibletimer.value = false;
        Message.error('新增失败！')

    }
};

// const changetimer = (e) => {
//     console.log(e);

//     console.log(form.value.timer);


// }




const selectedKeys = ref([]);  //多选
const plxz = () => {

    if (selectedKeys.value.length == 0) {
        return Message.warning('请选择文件')

    }

    const selectedItems = tableList.value.filter(item =>
        selectedKeys.value.includes(item.id)
    );

    let myArray = []
    selectedItems.forEach((res) => {

        myArray.push({
            name: res.name,
            url: qrCodeUrl(res.qrCodeUrl),
            location: res.location,
            imei: res.imei

        })
    })


    downloadpic.value.getData(myArray)


    nextTick(() => {
        downloadpic.value.examScoreResultList(myArray)

    })





}

let loading = ref(false);
let formData = ref({
    page: 1,
    size: 10,
});
const pagination = ref({
    current: formData.value.page,
    pageSize: formData.value.size,
    showTotal: true,
    showJumper: true,
    "show-page-size": true,
    total: 0
}); // 分页属性
const columns = ref([
    {
        title: '网点名称',
        width: '150',
        dataIndex: 'name',
    },
    {
        title: '使用时间',
        width: '250',
        dataIndex: 'useTime',

    },
    {
        title: '所属终端',
        width: '150',
        dataIndex: 'imei',
    },
    {
        title: '网点位置',
        width: '150',
        dataIndex: 'location',
    },
    {
        title: '网点型号',
        width: '150',
        dataIndex: 'deviceType',
        slotName: 'deviceType',
    },
    {
        title: '网点状态',
        width: '100',
        dataIndex: 'status',
        slotName: 'status',
    },
    {
        title: '新建时间',
        width: '180',
        dataIndex: 'createdAt',
    },
    {
        title: '网点二维码',
        width: '150',
        slotName: 'qrCodeUrl',
        dataIndex: 'qrCodeUrl',
    },
    {
        title: '操作',
        width: '270',
        align: 'center',
        fixed: 'right',
        dataIndex: 'operations',
        slotName: 'operations',
    },
])
const tableList = ref([]);

const onPageChange = (current) => {
    formData.value.page = current;
    pagination.value.current = current;
    selectedKeys.value = []
    getdevicfindAll()
};

const pagesizechange = (pageSize) => {
    formData.value.page = 1;
    pagination.value.current = 1;

    formData.value.size = pageSize;
    pagination.value.pageSize = pageSize;
    getdevicfindAll()


}

//获取设备列表
const getdevicfindAll = async () => {
    loading.value = true;
    try {
        let res = await devicfindAll(formData.value);


        tableList.value = res.data.content

        pagination.value.total = res.data.totalElements;
        loading.value = false;
    } catch (error) {
        loading.value = false;

    }

}

//打开新增或者编辑
let isShowEditNaame = ref('')
const openPage = async (name, data) => {
    isShowEditNaame.value = name
    isShowEdit.value = true;
    form.value = {} //先清空表单
    formRef.value.resetFields() //清空校验

    if (isShowEditNaame.value == '查看') {
        form.value = JSON.parse(JSON.stringify(data))
    }


    if (isShowEditNaame.value == '编辑') {
        try {
            let res = await wechatfindByDeviceSn(data.id)

            form.value = res.data
            if (form.value.useTime) {
                let sw = form.value.useTime.split('|')[0]
                let xw = form.value.useTime.split('|')[1]
                form.value.sw = sw.split('-')
                form.value.xw = xw.split('-')
            }


        } catch (error) {

        }
    }
}


//新增
let isShowEdit = ref(false);
const loadingEdit = ref(false);
const formRef = ref()
let form = ref({})
const handleOk = async () => {

    let rs = await formRef.value.validate();
    if (rs) return
    if (isShowEditNaame.value == '新增') {
        setdevicesadd()

    }
    if (isShowEditNaame.value == '编辑') {
        setquick_durationsupdate()
    }


}

//新增设备
const setdevicesadd = async () => {

    try {
        loadingEdit.value = true
        let res = await devicesadd(form.value)
        Message.success('新增成功')
        loadingEdit.value = false
        getdevicfindAll() //获取列表
        isShowEdit.value = false
    } catch (error) {
        loadingEdit.value = false
        Message.error('新增失败！')
    }
}

//编辑规则
const setquick_durationsupdate = async () => {



    try {
    if (form.value.sw && orm.value.sw.length > 0 && form.value.sw && form.value.sw.length > 0) {
        form.value.useTime = `${form.value.sw[0]}-${form.value.sw[1]}|${form.value.xw[0]}-${form.value.xw[1]}`
        
    }
        let res = await end_backupdate(form.value.id, form.value)
        Message.success('编辑成功')
        loadingEdit.value = false
        getdevicfindAll() //获取列表
        isShowEdit.value = false
    } catch (error) {
        loadingEdit.value = false
        Message.error('编辑失败！')

    }
}

//删除设备
const deleteOneOrder = async (id) => {
    try {
        let res = await devicesdelete(id, {})
        Message.success('删除成功')
        getdevicfindAll() //获取列表
    } catch (error) {
        Message.error('删除失败！')
    }
}

// 下载二维码
let downloadpic = ref()
const downloadQRCode = (data) => {
    // qrCodeUrl(record.qrCodeUrl)

    let myArray = [
        {
            name: data.name,
            url: qrCodeUrl(data.qrCodeUrl),
            location: data.location,
            imei: data.imei
        }
    ]



    downloadpic.value.getData(myArray)
    nextTick(() => {
        downloadpic.value.saveImage(myArray)

    })

};




//获取imci列表
let imeiList = ref([]);
let imeiFomdata = ref({
    page: 1,
    size: 1000,
})
let imeilTotol = ref(0)
let getrecordsfindAll = async () => {
    try {
        let res = await recordsfindAll(imeiFomdata.value)
        imeiList.value =  imeiList.value.concat(res.data.content)
        imeilTotol.value =  res.data.totalElements
        console.log(imeiList.value, 'dd22');

    } catch (err) {

    }
}

//搜索下来选
const handleSearch = (e) => {
    imeiFomdata.value.name = e
    imeiFomdata.value.page = 1
      imeiList.value =[]

      setTimeout(()=>{
     getrecordsfindAll()

      },1000)


}
//滚动底部修改
const handleReachBottom = (e) => {

    if (imeiList.value.length <  imeilTotol.value) {
        imeiFomdata.value.page++
        getrecordsfindAll()
    }

};


//显示64
const qrCodeUrl = (base64Data) => {
    return `data:image/png;base64,${base64Data}`;
}


//上传tup
const fileList = [];
const customRequest = async (option) => {
    const { onProgress, onError, onSuccess, fileItem, name } = option


    try {
        const formData = new FormData();
        formData.append('files', fileItem.file);
        let res = await repairsupload(formData)
        console.log(res);
        if (res.code == 200) {
            if (res.data && res.data.length > 0) {
                form.value.images = baseUrl + res.data[0]

                onSuccess(res.data);
                console.log(form.value);

            }
        }

    } catch (error) {
        onError(error)
    }




}


onMounted(() => {
    getdevicfindAll()
    getrecordsfindAll()
})
</script>
<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;

    .search-btn {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        gap: 0 10px;
    }


    .container-table {
        margin-top: 20px;

        .general-card {
            box-sizing: border-box;
            padding: 20px 0;
        }
    }
}
</style>
